package search.backtracking;

import java.util.ArrayList;
import java.util.List;

/**
 * @Classname : CombinationSum
 * @Description : 39. 组合总和
 * https://leetcode.cn/problems/combination-sum/
 * @Author : chentianyu
 * @Date 2023/3/13 22:41
 */


public class CombinationSum {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> combine = new ArrayList<>();
        backTracking(candidates, target, ans, combine, 0);
        return ans;
    }

    private void backTracking(int[] candidates, int target, List<List<Integer>> ans, List<Integer> combine, int idx) {
        if (idx == candidates.length) return;  // 遍历到最后一个数字
        if (target == 0) {  // 到达目标值
            ans.add(new ArrayList<>(combine));
            return;
        }
        // 不选择当前数字
        backTracking(candidates, target, ans, combine, idx + 1);
        // 选择当前数字
        if (target - candidates[idx] >= 0) {
            combine.add(candidates[idx]);
            backTracking(candidates, target - candidates[idx], ans, combine, idx);
            combine.remove(combine.size() - 1);
        }
    }

}
